Page({
  onReady (e) {
    // 使用 wx.createAudioContext 获取 audio 上下文 context
    if(this.data.zh=='wx.createAudioContext'||this.data.zh=='AudioContext.play'||this.data.zh=='AudioContext.seek'||this.data.zh=='AudioContext.pause'||this.data.zh=='AudioContext.setSrc'){
      this.audioCtx1 = wx.createAudioContext('myAudio')
    this.audioCtx1.setSrc('https://sf1-cdn-tos.huoshanstatic.com/obj/media-fe/xgplayer_doc_video/music/audio.mp3')
    this.audioCtx1.play()
    } 
  },
  /**
   * 页面的初始数据
   */
  data: {
    schema: [],
    zh: '',
    title: '',
    remark: '',
    webUrl: '',
    formData: {},
    result: '',
    poster: 'http://y.gtimg.cn/music/photo_new/T002R300x300M000003rsKF44GyaSk.jpg?max_age=2592000',
    name: '此时此刻',
    author: '许巍',
    src: 'https://sf1-cdn-tos.huoshanstatic.com/obj/media-fe/xgplayer_doc_video/music/audio.mp3',
    audioCtx1:null
  },
  onLoad(options) {
    wx.setNavigationBarTitle({
      title: options.title,
    })

    this.setData({
      apiType: options.zh,
      title: options.title,
      zh: options.zh,
      remark: options.remark,
      webUrl: options.webUrl
    })
  },
  getFormData(e) {},
  /**
   * 验证BufferSourceNode.connect()是否连接成功
   * @param {AudioContext} audioContext - 音频上下文实例
   * @returns {Promise<boolean>} - 连接成功返回true，失败返回false
   */
  verifyBufferSourceConnection(audioContext) {
    return new Promise((resolve) => {
      try {
        // 创建一个空的音频缓冲区（1秒的静音音频）
        const buffer = audioContext.createBuffer(1, audioContext.sampleRate, audioContext.sampleRate);

        // 创建BufferSourceNode
        const source = audioContext.createBufferSource();
        source.buffer = buffer;

        // 创建一个增益节点作为中间目标
        const gainNode = audioContext.createGain();

        // 标记连接状态的变量
        let isConnected = false;

        // 监听源节点的结束事件，证明连接有效且音频已播放
        source.onended = () => {
          resolve(isConnected);
        };

        // 尝试连接
        try {
          // 连接到增益节点，再连接到目的地
          source.connect(gainNode);
          gainNode.connect(audioContext.destination);

          // 简单验证：检查连接是否存在（微信小程序的实现可能有差异）
          // 注意：标准Web Audio API没有直接的方法检查连接，这里用间接方式
          isConnected = true;

          // 播放音频以验证整个链路是否通畅
          source.start(0);

          // 设置超时，防止长时间没有响应
          setTimeout(() => {
            if (!source.onended) {
              resolve(false);
            }
          }, 1500);
        } catch (connectError) {
          console.error('连接过程出错:', connectError);
          resolve(false);
        }
      } catch (error) {
        console.error('创建音频节点出错:', error);
        resolve(false);
      }
    });
  },
  choose1() {
    const innerAudioContext = wx.createAudioContext('myAudio', this)
    this.setData({
      result: innerAudioContext
    })
  },
  choose2() {
    const innerAudioContext = wx.createInnerAudioContext({
      useWebAudioImplement: false // 是否使用 WebAudio 作为底层音频驱动，默认关闭。对于短音频、播放频繁的音频建议开启此选项，开启后将获得更优的性能表现。由于开启此选项后也会带来一定的内存增长，因此对于长音频建议关闭此选项
    })
    this.setData({
      result: innerAudioContext
    })
    },
    choose3() {
      const query = wx.createMediaAudioPlayer()
        this.setData({
          result: query
        })
      },
      choose4() {
        const audioCtx = wx.createWebAudioContext()
const loadAudio = (url) => {
  return new Promise((resolve) => {
    wx.request({
      url,
      responseType: 'arraybuffer',
      success: res => {
        console.log('res.data', res.data)
        this.setData({
          result: res
        })
        audioCtx.decodeAudioData(res.data, buffer => {
          resolve(buffer)
        }, err => {
          console.error('decodeAudioData fail', err)
          reject()
        })
      },
      fail: res => {
        console.error('request fail', res)
        reject()
      }
    })
  })
}

const play = () => {
  loadAudio('https://sf1-cdn-tos.huoshanstatic.com/obj/media-fe/xgplayer_doc_video/music/audio.mp3').then(buffer => {
    let source = audioCtx.createBufferSource()
    source.buffer = buffer
    source.connect(audioCtx.destination)
    source.start()
  }).catch(() => {
    console.log('fail')
  })
}

play()
        },
        choose5() {
          const query = wx.createVideoDecoder()
            this.setData({
              result: query
            })
          },
          choose6(){
            const audioCtx = wx.createWebAudioContext()
wx.request({
  url: 'https://sf1-cdn-tos.huoshanstatic.com/obj/media-fe/xgplayer_doc_video/music/audio.mp3', // 音频 url
  responseType: 'arraybuffer',
  success: res => {
    audioCtx.decodeAudioData(res.data, audioBuffer => {
      const channels = audioBuffer.numberOfChannels;
      const frameCount = audioCtx.sampleRate * 2.0;
      const anotherArray = new Float32Array(frameCount);
      const rate = audioBuffer.sampleRate
      const startOffset = 0
      const endOffset = rate * 3;
      const newAudioBuffer = audioCtx.createBuffer(channels,endOffset - startOffset,rate)
      const offset = 0
      for (let channel = 0; channel < channels; channel++) {
        audioBuffer.copyFromChannel(anotherArray, channel, startOffset);
        console.log('copyFromChannel 成功')
        newAudioBuffer.copyToChannel(anotherArray, channel, offset);
        const myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate);
      // const nowBuffering = myArrayBuffer.getChannelData(channel);
          
      } 
      this.setData({
        result: "连接成功"
      })  
    }, err => {
      console.error('decodeAudioData fail', err)
    })
  }
})
            // try {
            //   // 创建音频上下文（微信小程序中需要在用户交互事件中创建）
            //   const audioContext = wx.createWebAudioContext();
              
            //   // 验证连接
            //   const isSuccess =this.verifyBufferSourceConnection(audioContext);
            //  let results ="";
            //   if (isSuccess) {
            //     results='BufferSourceNode连接成功'
            //     console.log('BufferSourceNode连接成功');
            //   } else {
            //     results='BufferSourceNode连接失败'
            //     console.log('BufferSourceNode连接失败');
            //   }
            //   this.setData({
            //     result: results
            //   })
            //   return isSuccess;
            // } catch (error) {
            //   console.error('测试连接时发生错误:', error);
            //   return false;
            // }
          },
          
  audioPlay: function () {
    this.audioCtx1.play()
  },
  audioPause: function () {
    this.audioCtx1.pause()
  },
  audio14: function () {
    this.audioCtx1.seek(14)
  },
  audioStart: function () {
    this.audioCtx1.seek(0)
  },
  setSrcaudio:function(){
    this.audioCtx1.setSrc('https://sf1-cdn-tos.huoshanstatic.com/obj/media-fe/xgplayer_doc_video/music/audio.mp3')
  }
})